import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'

interface PieChartProps {
  data: Array<{
    name: string
    value: number
  }>
  title?: string
  loading?: boolean
  height?: number
  style?: React.CSSProperties
  radius?: string | string[]
  roseType?: boolean
}

const PieChart: React.FC<PieChartProps> = ({
  data,
  title,
  loading,
  height = 400,
  style,
  radius = ['50%', '70%'],
  roseType = false
}) => {
  const chartRef = useRef<HTMLDivElement>(null)
  const chartInstance = useRef<echarts.ECharts>()

  useEffect(() => {
    if (!chartRef.current) return

    chartInstance.current = echarts.init(chartRef.current)

    const option: EChartsOption = {
      title: title ? { text: title } : undefined,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: title || '数据',
          type: 'pie',
          radius,
          roseType: roseType ? 'radius' : undefined,
          data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ],
      loading
    }

    chartInstance.current.setOption(option)

    return () => {
      chartInstance.current?.dispose()
    }
  }, [data, title, loading, radius, roseType])

  useEffect(() => {
    const handleResize = () => {
      chartInstance.current?.resize()
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return (
    <div 
      ref={chartRef} 
      style={{ height, ...style }}
    />
  )
}

export default PieChart 